package pkg

import (
	"context"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"log"

	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
)

const (      
	AppID = " xxxxxxxxxxxxxxxxx" // 替换为你的微信应用ID
	MchID = " xxxxxxxxxxxxxxxxx"         // 替换为你的商户ID
	
	NotifyURL = " xxxxxxxxxxxxxxxxx"
	// 替换为你的支付结果通知URL
	MchAPIv3Key                = " xxxxxxxxxxxxxxxxx"         //v3密钥
	MchCertificateSerialNumber = " xxxxxxxxxxxxxxxxx" //证书序列号；

)

var MchPrivateKey, err = utils.LoadPrivateKeyWithPath("pkg/weixinpay/lss/apiclient_key.pem")

func pay() {
	// 使用 utils 提供的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
	//mchPrivateKey, err: = utils.LoadPrivateKeyWithPath("/pkg/weixinpay/apiclient_key.pem")
	mchPrivateKey, err := utils.LoadPrivateKeyWithPath("/pkg/weixinpay/lss/apiclient_key.pem")
	if err != nil {
		fmt.Println("load merchant private key error123:", err)
	}
	ctx := context.Background()
	// 使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(MchID, MchCertificateSerialNumber, mchPrivateKey, MchAPIv3Key),
	}
	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		log.Fatalf("new wechat pay client err:%s", err)
	}
	// 以 Native 支付为例
	svc := native.NativeApiService{Client: client}
	// 发送请求
	resp, result, err := svc.Prepay(ctx,
		native.PrepayRequest{
			Appid:       core.String(" xxxxxxxxxxxxxxxxx"),
			Mchid:       core.String(" xxxxxxxxxxxxxxxxx"),
			Description: core.String("Image形象店-深圳腾大-QQ公仔"),
			OutTradeNo:  core.String("1217752501201407033233368018"),
			Attach:      core.String("自定义数据说明"),
			NotifyUrl:   core.String("https://www.weixin.qq.com/wxpay/pay.php"),
			Amount: &native.Amount{
				Total: core.Int64(100),
			},
		},
	)
	// 使用微信扫描 resp.code_url 对应的二维码，即可体验Native支付
	log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
}

// if err != nil {
// fmt.Println("load merchant private key error123")
// }
// 初始化微信支付
func InitWeChatPay() *core.Client {
	//mchPrivateKey, err := utils.LoadPrivateKeyWithPath("pkg/weixinpay/lss/apiclient_key.pem")
	//if err != nil {
	//	fmt.Println("load merchant private key error123")
	//}
	//mchPrivateKey, err := utils.LoadPrivateKey(ApiKey)
	ctx := context.Background()
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(MchID, MchCertificateSerialNumber, MchPrivateKey, MchAPIv3Key),
	}
	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		log.Fatalf("new wechat pay client err:%s", err)
	}

	return client
}

// 验证签名：
// 验证微信支付通知的签名
func VerifyWeChatPayNotification(signature, timestamp, nonce, body, apiKey string) bool {
	// 将参数和API密钥拼接成字符串
	signStr := timestamp + "\n" + nonce + "\n" + body + "\n"
	// 使用 API 密钥对拼接后的字符串进行 HMAC-SHA256 签名
	mac := hmac.New(sha256.New, []byte(apiKey))
	mac.Write([]byte(signStr))
	expectedSignature := hex.EncodeToString(mac.Sum(nil))
	// 比较微信支付通知中的签名和预期的签名是否一致
	return signature == expectedSignature
}
